<template>
<view class="water-site-list">
  <view class="fill-base mt-md ml-md mr-md pd-lg radius-16" v-for="( item, index ) in list.data " :key=" index ">
    <water-site-item :info="item"></water-site-item>
  </view>

  <load-more :noMore=" list.current_page >= list.last_page && list.data.length > 0 && location.lng " :loading=" loading " v-if=" loading "></load-more>

  <block v-if=" !loading && list.data.length <= 0 && list.current_page == 1 ">
    <abnor v-if=" location.lat && location.lng "></abnor>
    <block v-if=" !location.lat && !location.lng ">
      <!-- #ifdef H5 -->
      <abnor type="NOT_LOCATION" title="暂无数据"></abnor>
      <!-- #endif -->
      <!-- #ifndef H5 -->
      <abnor type="NOT_LOCATION" title="暂无数据" @confirm="toOpenLocation"
      :button="[ { text: '开启定位' , type: 'confirm' } ]" btnSize=""></abnor>
      <!-- #endif -->
    </block>
  </block>

  <!-- #ifdef MP-WEIXIN -->
  <user-privacy ref="user_privacy" :show=" false " />
  <!-- #endif -->
</view>
</template>
<script>
import {
  mapState,
  mapActions,
  mapMutations
} from "vuex"
import waterSiteItem from "@/components/water-site/water-site-item.vue"

export default {
  name: "water-site-list", props: {
    options: { type: Object, default: {} },
  }, components: {
    waterSiteItem
  }, async mounted() {
    let { channel_id = 0 } = this.options
    if( channel_id ) {
      this.addScanRecord( { type: 1, qr_id: channel_id } )
    }
    this.options = channel_id ? await this.updateCommonOptions( this.options ) : this.options
    let { realtime_location = 0 } = this.configInfo
    console.log( this.configInfo );
    console.log( this.pageActive );
    console.log( this.thisPage );
    console.log( 'banner', this.banner );
    console.log( 'service_cate', this.service_cate );
    console.log( 'recommend_list', this.recommend_list );
    let {
      pageActive,
      changeAddr
    } = this
    if( !pageActive ) {
      this.$util.showLoading()
    }
    uni.onNetworkStatusChange( ( res ) => {
      var { isConnected } = res
      if( isConnected && ( !pageActive || ( pageActive && ( realtime_location || changeAddr ) ) ) ) {
        return this.init()
      }
    } )
    await this.init();
    // #ifdef H5
    // #endif
    var { app_text } = this.configInfo
    uni.setNavigationBarTitle( {
      title: app_text || '首页'
    } )
  }, async onShow() {
    // #ifdef H5
    if( this.$jweixin.isWechat() ) {
      await this.$jweixin.initJssdk();
      this.toAppShare()
    }
    var { app_text } = this.configInfo
    uni.setNavigationBarTitle( {
      title: app_text || '首页'
    } )
    // #endif
    if( this.haveShieldOper == 2 ) {
      await this.initIndex()
      this.updateUserItem( {
        key: 'haveShieldOper',
        val: 0
      } )
    }
    if( this.pageActive && this.userInfo.id ) {
      await this.getCouponList()
    }
    if( !this.location.lat && this.locaRefuse ) {
      await this.toResetUtilLoca()
    }
  }, onPullDownRefresh() {
    // #ifndef APP-PLUS
    uni.showNavigationBarLoading()
    // #endif
    this.updateUserItem( {
      key: 'changeAddr',
      val: false
    } )
    this.initRefresh();
    uni.stopPullDownRefresh()
  }, onReachBottom() {
    if( this.list.current_page >= this.list.last_page || this.loading ) return;
    this.loading = true;
    this.getList( this.param.page + 1 );
  }, onShareAppMessage( e ) {
    let {
      id: pid = 0
    } = this.userInfo
    let path = `/pages/service?pid=${ pid }`
    this.$util.log( path )
    return { title: '', imageUrl: '', path, }
  }, watch: {
    locaRefuse( newval, oldval ) {
      if( !newval ) {
        this.toResetUtilLoca()
      }
    }, changeOnAddr( newval, oldval ) {
      let {
        noloca,
      } = this.noChangeLoca
      if( newval && noloca ) {
        this.initUtilLocaData()
      }
    }, noChangeLoca( newval, oldval ) {
      setTimeout( () => {
        let { lat, lng, unix = 0 } = this.changeOnAddr
        let {
          noloca
        } = this.noChangeLoca
        let cur_unix = this.$util.DateToUnix( this.$util.formatTime( new Date(), 'YY-M-D h:m:s' ) )
        if( noloca && ( ( !lat && !lng ) || !unix || ( unix && ( cur_unix - unix >= 1 ) ) ) ) {
          this.getUtilLocation()
        }
      }, 800 )
    }
  }, data() {
    return {
      couponList: [], //优惠券
      coupon_discount: 0, //优惠券
      isLoad: false,
      loading: true,
      lockTap: false,
      openMiniForm: {}
    }
  }, computed: mapState( {
    pageActive: state => state.service.pageActive,
    activeIndex: state => state.service.activeIndex,
    tabList: state => state.service.tabList,
    param: state => state.service.param,
    list: state => state.WaterSite.list,
    banner: state => state.service.banner,
    service_cate: state => state.service.service_cate,
    recommend_list: state => state.service.recommend_list,
    recommend_style: state => state.service.recommend_style,
    have_coupon: state => state.service.have_coupon,
    primaryColor: state => state.config.configInfo.primaryColor,
    subColor: state => state.config.configInfo.subColor,
    configInfo: state => state.config.configInfo,
    autograph: state => state.user.autograph,
    userInfo: state => state.user.userInfo,
    location: state => state.user.location,
    locaRefuse: state => state.user.locaRefuse,
    changeAddr: state => state.user.changeAddr,
    isGzhLogin: state => state.user.isGzhLogin,
    haveShieldOper: state => state.user.haveShieldOper,
    userCoachStatus: state => state.user.userCoachStatus,
    useChooseLocation: state => state.user.useChooseLocation,
    changeOnAddr: state => state.user.changeOnAddr,
    noChangeLoca: state => state.user.noChangeLoca,
    scanRecordId: state => state.user.scanRecordId,
    thisPage: state => state.config.configInfo.page ? state.config.configInfo.page[ 1 ] : null,
  } ), methods: {
    ...mapActions( [
      'getConfigInfo',
      'getUserInfo',
      'updateCommonOptions',
      'addScanRecord',
      'updateScanRecord',
      'getServiceIndex',
      'getRecommendList',
      'getWaterSiteList',
      'getServiceList'
    ] ), ...mapMutations( [
      'updateUserItem',
      'updateServiceItem',
      'updateTechnicianItem',
      'updateMapItem',
      'updateDynamicItem',
      'updateShopstoreItem'
    ] ), async init( refresh = false ) {
      if( !this.configInfo.id || refresh ) {
        await this.getConfigInfo()
      }
      var { pid = 0, channel_id = 0 } = this.options
      var { realtime_location: rloca = 0 } = this.configInfo
      if( !refresh && this.pageActive && ( !rloca && !this.changeAddr ) && ( !pid || !channel_id ) ) {
        this.isLoad = true
        this.loading = false
        return this.$util.hideAll()
      }

      // #ifdef H5
      if( this.isGzhLogin ) {
        setTimeout( () => {
          this.toBindChannel()
        }, 1000 )
      } else {
        await this.toBindChannel()
      }
      // #endif
      // #ifndef H5
      await this.toBindChannel()
      // #endif

      await this.getServiceIndex()
      this.isLoad = true


      var { location, locaRefuse, changeAddr } = this
      var { plugAuth = {}, realtime_location = 0 } = this.configInfo
      var { recommend = false } = plugAuth
      var { status: coach_status, coach_position } = this.userCoachStatus

      console.log( 'here' );
      if(
          // #ifdef APP-PLUS
          !locaRefuse &&
          // #endif
          ( ( realtime_location && !changeAddr ) || ( !realtime_location && recommend && !location.lat ) )
      ) {

        // #ifdef MP-WEIXIN
        let privacyCheck = this.$refs.user_privacy.check()
        console.log( 'privacyCheck', privacyCheck );
        if( privacyCheck ) {
          this.$refs.user_privacy.open()
          this.loading = false
          return this.$util.hideAll()
        }
        // #endif
        console.log( 'initIndex' );
        if( coach_status == 2 && coach_position ) {
          let {
            lat: change_lat = 0,
            lng: change_lng = 0,
            unix = 0
          } = this.changeOnAddr
          let cur_unix = this.$util.DateToUnix( this.$util.formatTime( new Date(), 'YY-M-D h:m:s' ) )
          let noloca = !( change_lat && change_lng && ( unix && ( cur_unix - unix < 3 ) ) )
          if( !noloca ) {
            let loca = Object.assign( {}, this.location, {
              lat: change_lat,
              lng: change_lng,
              is_util_loca: 1
            } )
            this.updateUserItem( {
              key: 'location',
              val: loca
            } )
          }
          this.updateUserItem( {
            key: 'noChangeLoca',
            val: {
              noloca
            }
          } )
          if( this.noChangeLoca.noloca ) return
          await this.initUtilLocaData()
        } else {
          await this.getUtilLocation()
        }
        return
      }
      await this.initUtilLocaData()
    }, async getUtilLocation() {
      // #ifdef H5
      if( this.$jweixin.isWechat() ) {
        let wxReady = await this.$jweixin.wxReady2();
        let {
          latitude: lat = 0,
          longitude: lng = 0
        } = wxReady ? await this.$jweixin.getWxLocation() : {
          latitude: 0,
          longitude: 0
        }
        // await this.$jweixin.wxReady3()
        // let {
        // 	latitude: lat = 0,
        // 	longitude: lng = 0
        // } = await this.$jweixin.getWxLocation()
        let val = Object.assign( {}, this.location, { lat, lng, is_util_loca: 1 } )
        this.updateUserItem( { key: 'location', val } )
        await this.initUtilLocaData()
      }
      // #endif
      // #ifndef H5
      console.log( 'getUtilLocation' );
      var { lat = 0, lng = 0 } = await this.$util.getLocation()
      console.log( 'getLocation' );
      let val = Object.assign( {}, this.location, {
        lat,
        lng,
        is_util_loca: 1
      } )
      this.updateUserItem( {
        key: 'location',
        val
      } )
      await this.initUtilLocaData()
      // #endif
    }, async initUtilLocaData() {
      console.log( 'initUtilLocaData' );
      this.updateUserItem( { key: 'noChangeLoca', val: { noloca: false } } )
      let { lng = 0, lat = 0 } = this.location
      this.updateServiceItem( {
        key: 'pageActive',
        val: true
      } )
      this.$util.hideAll()

      var { plugAuth = {}, realtime_location = 0 } = this.configInfo
      var { recommend = false } = plugAuth

      // #ifndef H5
      if(
          // #ifdef APP-PLUS || MP-WEIXIN
          !lat && !lng &&
          // #endif
          // #ifdef MP-WEIXIN
          ( realtime_location || ( !realtime_location && recommend ) ) &&
          // #endif
          true
      ) {
        if( this.userInfo.id && this.have_coupon ) {
          await this.getCouponList()
        }
        this.updateServiceItem( {
          key: 'recommend_list',
          val: []
        } )
        this.updateServiceItem( {
          key: 'list',
          val: {
            data: [],
            last_page: 1,
            current_page: 1
          }
        } )
        this.loading = false
        return this.$util.hideAll()
      }
      // #endif

      if( recommend ) {
        await Promise.all( [ this.getRecommendList( { lat, lng } ), this.getList( 1 ) ] )
      } else {
        await this.getList( 1 )
      }

      if( ( realtime_location || ( !realtime_location && recommend ) ) && !this.changeAddr ) {
        this.$util.getMapInfo()
      }
      if( this.userInfo.id && this.have_coupon ) {
        await this.getCouponList()
      }
    }, handerTab( $event ) {
      console.log( $event );
      uni.navigateTo( {
        url: $event,
      } )
    }, toSearch( $event ) {
      console.log( 'toSearch', $event );
    }, columnChange( $event ) {
      console.log( 'columnChange', $event );
      uni.navigateTo( {
        url: $event.href
      } );
    }, initRefresh() {
      this.initIndex( true )
    }, async toResetUtilLoca() {
      // #ifdef APP-PLUS
      let {
        lat: locaLat = 0
      } = this.location
      if( !locaLat && this.pageActive ) {
        let {
          lng = 0,
          lat = 0
        } = await this.$util.getUtilLocation()
        if( !lat && !lng ) return
        this.$refs.open_location_info.pShow = false
        let {
          recommend
        } = this.configInfo.plugAuth
        if( recommend ) {
          await Promise.all( [ this.getRecommendList( {
            lat,
            lng
          } ), this.getList( 1 ) ] )
        } else {
          await this.getList( 1 )
        }
        this.$util.getMapInfo()
        let updateArr = [ 'updateTechnicianItem', 'updateMapItem',
          'updateDynamicItem', 'updateShopstoreItem'
        ]
        updateArr.map( item => {
          this[ item ]( {
            key: 'pageActive',
            val: false
          } )
        } )
      }
      // #endif
    }, async toOpenLocation() {
      // #ifdef MP-WEIXIN
      let privacyCheck = this.$refs.user_privacy.check()
      if( privacyCheck ) {
        this.$refs.user_privacy.open()
        return
      }
      // #endif
      await this.$util.checkAuth( {
        type: 'userLocation',
        checkApp: true
      } )
      // #ifdef MP-WEIXIN
      await this.initIndex()
      // #endif
    }, async getList( page = 0 ) {
      let { realtime_location = 0 } = this.configInfo
      if( page ) {
        let { tabList, activeIndex } = this
        let { service_filter = true } = this.banner
        if( !service_filter ) {
          activeIndex = 0
        }
        let { sort, sign } = tabList[ activeIndex ]

        if( realtime_location && activeIndex == 0 ) {
          sort = 'type desc'
        }
        let desc = activeIndex == 0 || sign == 1 ? '' : 'desc'
        this.updateServiceItem( { key: 'param', val: { page: page, sort: `${ sort } ${ desc }` } } )
      }
      this.loading = true
      let { list: oldList, location } = this
      let { lng = 0, lat = 0 } = location
      if(
          !lat && !lng
          // #ifndef APP-PLUS
          && realtime_location
          // #endif
      ) {
        this.loading = false
        this.$util.hideAll()
        return
      }

      let param = Object.assign( {}, this.param, { lat, lng, size: 10 } )
      // await this.getServiceList( param )
      await this.getWaterSiteList( param )
      // this.updateServiceItem( { key: 'list', val: data } )
      // console.log( data );
      this.loading = false
      this.$util.hideAll()
    }, handerTabChange( index ) {
      this.updateServiceItem( {
        key: 'activeIndex',
        val: index
      } )
      let tabList = this.$util.deepCopy( this.tabList )
      let {
        is_sign,
        sign,
      } = tabList[ index ];
      if( is_sign ) {
        tabList[ index ].sign = sign == 0 ? 1 : 0;
      }
      this.updateServiceItem( {
        key: 'tabList',
        val: tabList
      } )
      this.$util.showLoading()
      uni.pageScrollTo( {
        scrollTop: 0
      } )
      this.getList( 1 )
    }, async getCouponList() {
      let {
        lat,
        lng
      } = this.location
      let {
        discount = 0,
        list
      } = await this.$api.service.couponList( {
        lat,
        lng
      } )
      this.couponList = list
      this.coupon_discount = discount
      if( this.isLoad ) {
        if( discount * 1 > 0 ) {
          this.$refs.coupon_auto_item.open()
        }
        if( discount * 1 == 0 && list.length > 0 ) {
          this.$refs.coupon_item.open()
        }
      }
      this.loading = false
      this.$util.hideAll()
    }, toAppShare() {
      let {
        id: pid = 0
      } = this.userInfo
      let title = '首页'
      let {
        siteroot
      } = siteInfo
      let url = siteroot.split( '/index.php' )[ 0 ]
      let href = `${ url }/h5/#/pages/service?pid=${ pid }`
      let imageUrl = ''
      this.$jweixin.wxReady( () => {
        this.$jweixin.showOptionMenu()
        this.$jweixin.shareAppMessage( title, '', href, imageUrl )
        this.$jweixin.shareTimelineMessage( title, href, imageUrl )
      } )
    }, async toBindChannel() {
      let { pid = 0, channel_id = 0 } = this.options
      let { id = 0 } = this.userInfo
      if( ( pid || channel_id ) && !id ) {
        await this.getUserInfo()
      }
      let {
        id: uid
      } = this.userInfo
      if( channel_id && uid ) {
        await this.$api.user.bindChannel( {
          channel_id
        } )
      }
      if( this.scanRecordId ) {
        this.updateScanRecord()
      }
    }, goBanner( e ) { // 轮播图
      // connect_type 1查看大图，2文章
      let {
        connect_type,
        type_id: id = 0,
        img: current,
        linkType = 0,
        link = []
      } = e
      if( connect_type ) {
        switch( connect_type ) {
          case 1:
            this.$util.previewImage( {
              current,
              urls: [ current ]
            } )
            break;
          case 2:
            this.$util.goUrl( {
              url: `/user/pages/article?id=${ id }`
            } )
            break;
        }
        return
      }
      let {
        url
      } = link[ 0 ]
      this.toConfirmGoUrl( url, linkType, current[ 0 ].url )
    }, goCate( e ) { // 导航栏
      let {
        id,
        title,
        url = '',
        linkType = 0,
        link = [],
        img = []
      } = e
      if( linkType ) {
        url = link[ 0 ].url
      }
      if( !url ) {
        url =
            `/user/pages/service/list?id=${ id }&title=${ title }`
      }
      if( [ '/technician/pages/apply?type=1',
        '/agent/pages/apply'
      ].includes(
          url ) ) {
        this.$util.toCheckLogin( {
          url
        } )
        return
      }

      if( !linkType ) {
        return this.$util.goUrl( { url } )
      }
      this.toConfirmGoUrl( url, linkType, img[ 0 ].url, title )
    }, toConfirmGoUrl( url, linkType, current, title = '' ) {
      if( [ '/technician/pages/apply?type=1', '/agent/pages/apply' ].includes( url ) ) {
        this.$util.toCheckLogin( {
          url
        } )
        return
      }
      if( linkType == 5 ) {
        this.$util.previewImage( {
          current,
          urls: [ current ]
        } )
        return
      }

      let {
        methodObj
      } = this.configInfo
      let openType = methodObj[ linkType ]
      // #ifdef H5
      if( openType === 'web' ) {
        window.location.href = url
        return
      }
      if( openType === 'miniProgram' ) {
        let arr = url.split( ";" )
        let appid = arr[ 0 ]
        let path = arr.length > 1 ? arr[ 1 ] : ''
        this.openMiniForm = {
          title,
          appid,
          path,
          img: current
        }
        this.$refs.open_mini_program.open()
        return
      }
      // #endif
      this.$util.goUrl( {
        url,
        openType
      } )
    }, async userGetCoupon() {
      let ids = []
      this.couponList.forEach( v => {
        ids.push( v.id )
      } )
      let res = await this.$api.service
      .userGetCoupon( {
        coupon_id: ids
      } )
      this.$util.showToast( {
        title: `领取成功`
      } )
      setTimeout( () => {
        this.$util.goUrl( {
          url: '/user/pages/coupon/list'
        } )
      }, 1000 )
      this.$refs.coupon_item.close()
      this.loading = false
      this.$util.hideAll()
    }, async toCouponGetBtn() {
      this.$refs.coupon_auto_item.close()
      this.$util.goUrl( {
        url: '/user/pages/coupon/list'
      } )
    }, toTechnician( index ) {
      let {
        id,
        city_id,
        coach_name
      } = this.recommend_list[ index ]
      this.updateTechnicianItem( {
        key: 'pageActive',
        val: false
      } )
      this.$util.goUrl( {
        url: `/pages/technician?coach_id=${ id }&coach_name=${ coach_name }&city_id=${ city_id }`,
        openType: `reLaunch`
      } )
    }
  }
}
</script>
<style lang="scss" scoped>
.water-site-list {}
</style>
